package com.cedifie.lendapp.ui.user.act

import android.annotation.SuppressLint
import android.app.PendingIntent
import android.graphics.Color
import android.graphics.Typeface
import android.text.Editable
import android.text.TextWatcher
import android.view.Gravity
import android.view.View
import android.view.inputmethod.EditorInfo
import androidx.activity.result.IntentSenderRequest
import androidx.activity.result.contract.ActivityResultContracts
import com.cedifie.lendapp.R
import com.cedifie.lendapp.databinding.ActUserLoginBinding
import com.cedifie.lendapp.http.HttpHelper
import com.cedifie.lendapp.mvp.MvpAct
import com.cedifie.lendapp.ui.CedWelcomeAct
import com.cedifie.lendapp.ui.PaPoyAct
import com.cedifie.lendapp.ui.user.impl.CedUserLoginPresenterImpl
import com.cedifie.lendapp.ui.user.view.ICedUserLoginView
import com.cedifie.lendapp.utils.dialog.LoginCodeDialog
import com.cedifie.lendapp.utils.dialog.ReasonDialog
import com.cedifie.lendapp.utils.event.CedEventManager
import com.cedifie.lendapp.utils.event.CedEventType
import com.cedifie.lendapp.utils.helper.PermissionHelper
import com.cedifie.lendapp.utils.helper.SharedHelper
import com.cedifie.lendapp.weight.CedInputText
import com.google.android.gms.auth.api.identity.GetPhoneNumberHintIntentRequest
import com.google.android.gms.auth.api.identity.Identity
import com.lib.base.utils.helper.ActivityStackManager
import com.lib.base.utils.log.LogHelper
import com.lib.base.utils.thread.TimingThread
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import org.json.JSONObject

/**
 * Cedifie
 * @Author wwdeng
 * @CreateTime: 2024/6/14 16:25
 * @Annotation：
 */
class CedUserLoginAct: MvpAct<ICedUserLoginView, CedUserLoginPresenterImpl>(),ICedUserLoginView,TimingThread.ITimingThreadListener {

    lateinit var binding: ActUserLoginBinding

    //倒计时
    var count = 60
    private var timeThread: TimingThread? = null
    //验证码Dialog
    var mDialog: LoginCodeDialog? = null

    override fun getCedRootView(): View {
        binding = ActUserLoginBinding.inflate(layoutInflater)
        return binding.root
    }

    override fun initCedView() {
        setCedTitleBarVisibility(View.VISIBLE)
        setCedTitleBarColor(Color.parseColor("#FFF8F8F8"))
        setCedBackBtnVisibility(View.INVISIBLE)
        setCedRightBtnVisibility(View.INVISIBLE)
        setCedTextTitleGravity(Gravity.CENTER)
        setCedTextTitle(getString(R.string.app_name))

        //关闭所有页面
        ActivityStackManager.finishAllActivity(CedUserLoginAct::class.java)
        checkNextBtnState()
    }

    override fun initCedListener() {
        binding.layoutLogin.setOnClickListener {
            binding.editMobile.clearFocus()
        }
        binding.textMobile.setOnClickListener {
            HttpHelper.addCedEventAction(CedEventType.CLICK.CED_CLICK_USER_LOGIN_SELF_MOBILE,"")
            getCedLoginMobileAction()
        }
        //电话号码入框监听
        binding.editMobile.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
            }

            override fun afterTextChanged(s: Editable?) {
                checkNextBtnState()
                if (getMobile().isNotEmpty()) {
                    binding.editMobile.setTypeface(Typeface.create(Typeface.DEFAULT, Typeface.BOLD))
                } else {
                    binding.editMobile.setTypeface(Typeface.create(Typeface.DEFAULT, Typeface.NORMAL))
                }
            }
        })
        binding.editMobile.setOnEditorActionListener { _, actionId, _ ->
            if (actionId == EditorInfo.IME_ACTION_DONE) {
                binding.editMobile.clearFocus()
                true
            }
            false
        }
        //电话号码输入框焦点监听
        binding.editMobile.setInputFocusChangeListener(object : CedInputText.IInputFocusChangeListener {
            override fun onFocusChange(v: View?, hasFocus: Boolean) {
            }
            override fun onCompleteAction(v: View?, remark: String) {
                HttpHelper.addCedEventAction(CedEventType.FORM.CED_FORM_LOGIN_MOBILE, remark)
            }
        })

        //隐私政策切换
        binding.checkBox.setOnCheckedChangeListener { _, isChecked ->
            checkNextBtnState()
            when (isChecked) {
                true -> {
                    HttpHelper.addCedEventAction(CedEventType.CLICK.CED_CLICK_LOGIN_PRIVACY_AGREE, "")
                }

                false -> {
                    HttpHelper.addCedEventAction(CedEventType.CLICK.CED_CLICK_LOGIN_PRIVACY_DENY, "")
                }
            }
        }

        //Next
        binding.btnNext.setOnClickListener {
            HttpHelper.addCedEventAction(CedEventType.CLICK.CED_CLICK_LOGIN_NEXT, getMobile())
            //立即上报
            CedEventManager.getInstance().updateCedEventsNow()
            binding.editMobile.clearFocus()

            showCedLoading(getString(R.string.loading))
            //发送验证码
//            mvpPresenter?.sendCedSmsCodeAction()
            // TODO: 2025-04-09 改为后置校验流程
            mvpPresenter?.loginCedNoCodeAction()
        }

        // Privacy policy
        binding.privacyPolicy.setOnClickListener {
            onIntent(PaPoyAct::class.java)
        }
    }

    @SuppressLint("SetTextI18n")
    override fun initCedData() {
        //时区区号
        binding.textZoneCode.text = "+${SharedHelper.getCedSPString(SharedHelper.CED_SPKEY.CEDIFIE_TIMEZONE_CODE)}"

        //不显示百分比
        binding.circleSeekBar.setShowPercentText(false)
        val defaultAmount = mvpPresenter?.getAmount()
        defaultAmount?.let {
            if (it.isNotEmpty()){
                binding.circleSeekBar.max = it.toInt()
                binding.circleSeekBar.progress = it.toInt()
                binding.circleSeekBar.labelText = it
            }
        }
    }

    override fun createMvpPresenter(): CedUserLoginPresenterImpl {
        return CedUserLoginPresenterImpl(this)
    }

    /**
     * 设置按钮状态
     */
    private fun checkNextBtnState() {
        if (binding.checkBox.isChecked && getMobile().isNotEmpty()) {
            binding.btnNext.isEnabled = true
        } else {
            binding.btnNext.isEnabled = false
        }
    }

    /**
     * 显示验证码输入框dialog
     */
    override fun showCedSmsCodeDialog() {
        if (mDialog == null) {
            mDialog = LoginCodeDialog(this, object : LoginCodeDialog.IDialogCallback {
                //点击操作监听
                override fun onClick(view: View?) {
                    when (view?.id) {
                        R.id.ivClose -> {//关闭
                            if (timeThread != null) {
                                timeThread?.stopThread()
                            }
                            mDialog?.dismiss()
                        }

                        R.id.resendLayout -> {//重发
                            mvpPresenter?.sendCedSmsCodeAction()
                            HttpHelper.addCedEventAction(CedEventType.CLICK.CED_CLICK_LOGIN_VERIFY_CODE_RESEND, getMobile())
                        }

                        R.id.ivRefresh -> {//刷新
                            mvpPresenter?.sendCedSmsCodeAction()
                            HttpHelper.addCedEventAction(CedEventType.CLICK.CED_CLICK_LOGIN_VERIFY_CODE_REFRESH, getMobile())
                        }
                    }
                }

                //输入完成监听
                override fun inputComplete(content: String) {
                    onHideSoftInput(mDialog?.binding?.editCode)
                    HttpHelper.addCedEventAction(CedEventType.FORM.CED_FORM_LOGIN_VARIFY_CODE, "$content##${getMobile()}")
                    mvpPresenter?.loginCedAction(getMobile(), content,"NO")
                }
            })
            mDialog?.setCancelable(false)
            mDialog?.setCanceledOnTouchOutside(false)
        }
        mDialog?.let {
            if (!it.isShowing) {
                it.show()
                it.setMobile(getMobile())
                it.showCountdownLayout(count)
            }
        }
        startTimeThread()
    }

    /**
     * 启动倒计时
     */
    private fun startTimeThread() {
        if (timeThread != null) {
            timeThread?.stopThread()
        }
        count = 60
        mDialog?.showCountdownLayout(count)
        if (timeThread == null) {
            timeThread = TimingThread()
            timeThread?.setThreadDelayMillis(1000)
            timeThread?.setLoadListener(this)
        }
        timeThread?.startThread()
    }

    /**
     * 登录失败
     */
    override fun showCedLoginFailure(data: JSONObject) {
        //停止倒计时
        if (timeThread != null) {
            timeThread?.stopThread()
        }
        if (mDialog != null) {
            //显示验证码错误样式
            mDialog?.showWrongLayout()
        }
    }

    /**
     * 登录成功 进入欢迎页
     */
    override fun showCedWelcomePage() {
        //停止倒计时
        if (timeThread != null) {
            timeThread?.stopThread()
        }
        if (mDialog != null) {
            mDialog?.dismiss()
        }

        onIntent(CedWelcomeAct::class.java)
        finish()
    }

    override fun onLoading() {
        if (count <= 1) {
            count = 60
            timeThread?.stopThread()
            mDialog?.showRefreshLayout()
            return
        }
        count--
        mDialog?.onRefreshCountdown(count)
    }

    /**
     * 获取手机号码
     */
    override fun getMobile(): String {
        return binding.editMobile.text.toString()
    }

    /**
     * 获取本机手机号码
     */
    private fun getCedLoginMobileAction(){
        val request: GetPhoneNumberHintIntentRequest = GetPhoneNumberHintIntentRequest.builder().build()
        Identity.getSignInClient(this)
            .getPhoneNumberHintIntent(request)
            .addOnSuccessListener { result: PendingIntent ->
                try {
                    showCedPhoneNumberReasonDialog(result)
                } catch (e: Exception) {
                    LogHelper.e("Launching the PendingIntent failed")
                    showCedLoginMobileEditTextView()
                }
            }
            .addOnFailureListener {
                LogHelper.e("Phone Number Hint failed : OnFailureListener")
                showCedLoginMobileEditTextView()
            }
    }

    private val phoneNumberHintIntentResultLauncher = registerForActivityResult(
        ActivityResultContracts.StartIntentSenderForResult()) { result ->
        try {
            var phoneNumber = Identity.getSignInClient(this).getPhoneNumberFromIntent(result.data)
            LogHelper.e(">>>>>>>>>>>>>>>>>>>>>>>Phone Number $phoneNumber")
            HttpHelper.addCedEventAction(CedEventType.FORM.CED_FORM_USER_LOGIN_SELF_MOBILE,phoneNumber)
            //时区区号
            val zoneCode = "+${SharedHelper.getCedSPString(SharedHelper.CED_SPKEY.CEDIFIE_TIMEZONE_CODE)}"
            phoneNumber = phoneNumber.replace(zoneCode,"")
            binding.editMobile.setText(phoneNumber)
            binding.editMobile.visibility = View.VISIBLE
            binding.textMobile.visibility = View.GONE
            binding.editMobile.requestFocus()
            binding.editMobile.setSelection(getMobile().length)
        } catch(e: Exception) {
            LogHelper.e("Phone Number Hint failed：${e.message}")
            e.message?.let {
                HttpHelper.addCedEventAction(CedEventType.CLICK.CED_CLICK_USER_LOGIN_SELF_MOBILE_CANCEL,it)
            }
            showCedLoginMobileEditTextView()
        }
    }

    /**
     * 显示手机号码输入框
     */
    private fun showCedLoginMobileEditTextView(){
        binding.editMobile.visibility = View.VISIBLE
        binding.textMobile.visibility = View.GONE

        launch(Dispatchers.Main){
            delay(200)
            binding.editMobile.requestFocus()
            onShowSoftInput(binding.editMobile)
            binding.editMobile.setSelection(getMobile().length) // 将光标设置到文本末尾
        }
    }

    /**
     * 电话号码申明
     */
    private fun showCedPhoneNumberReasonDialog(result: PendingIntent){
        val item = PermissionHelper.getCedPhoneNumberPermissionItem()
        val permission = item.optString("permission")
        val reasonDialog = ReasonDialog(this,permission,object: ReasonDialog.IDialogCallback{
            override fun onReasonDenyClick() {
                HttpHelper.addCedEventAction(CedEventType.CLICK.CED_CLICK_PERMISSION_DENY,permission)
                showCedLoginMobileEditTextView()
            }
            override fun onReasonAgreeClick() {
                HttpHelper.addCedEventAction(CedEventType.CLICK.CED_CLICK_PERMISSION_AGREE,permission)
                phoneNumberHintIntentResultLauncher.launch(IntentSenderRequest.Builder(result).build())
            }
        })
        reasonDialog.setCancelable(true)
        reasonDialog.setCanceledOnTouchOutside(true)
        reasonDialog.show()
        reasonDialog.showCedPermissionItemViews(item)
    }


    override fun onStart() {
        super.onStart()
        HttpHelper.addCedEventAction(CedEventType.PAGE.CED_PAGE_LOGIN_START, "")
    }

    override fun onDestroy() {
        super.onDestroy()
        HttpHelper.addCedEventAction(CedEventType.PAGE.CED_PAGE_LOGIN_END, "")
        if (timeThread != null) {
            timeThread?.stopThread()
            timeThread = null
        }
        if (mDialog != null) {
            mDialog = null
        }
    }

}